using System;
using System.Reflection;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Globalization;

using SBPweb.Localization;

using SBPweb.Modules.Modularity;
using SBPweb.Contracts;
using SBPweb.Contracts.Options;

using SBPweb.Presentation.Windows.Forms.Controls;

using SBPweb.Modules.Options.Controls;
using SBPweb.Contracts.Implementation;

// This alias is needed for the module loader to recognize the module's entry point
[assembly: AssemblyDefaultAlias("SBPweb.Modules.Options.OptionsModule")]

namespace SBPweb.Modules.Options
{
    public class OptionsModule : ModuleBase, IOptionsService
	{

		#region Private members

		private OptionsForm optionsForm;
		private CommonTabPage mCommonTabPage;

        #endregion

		#region Public members

		public bool IsModified
		{
			get
			{
				if (optionsForm == null)
				{
					return false;
				}
				return optionsForm.IsModified;
			}
			set
			{
				if (optionsForm != null)
				{
					optionsForm.IsModified = value;
				}
				else
				{
					throw new NullReferenceException("OptionsForm is not exists.");
				}
			}
		}

		#endregion

		#region Constructor logic

		public OptionsModule(IModuleHost host)
            : base(host)
        {
            Name = "SBPweb.Modules.Options";
			pAsyncLoad = false;

			optionsForm = new OptionsForm(this);
			optionsForm.IsVisible = false;

            Services.Add(typeof(IOptionsService), this);
        }

		void Host_OnApplicationClosing(object sender, EventArgs e)
		{
			if (optionsForm != null)
			{
				optionsForm.IsVisible = false;
			}
		}

        public override void Initialize()
        {
            if (HostType != ModuleHostType.WindowsForms)
            {
				Host.LogManager.WriteError(this, "The HostType is not WinForms!", "Options");
				return;
            }

            pIcon = Properties.Resources.ControlPanel;

            LocalizationExtender.OnInvalidatingControls += new EventHandler(LocalizationExtender_OnInvalidatingControls);

            /*
            Host.Smartparts.Add(new OptionsForm(this));
            Host.Smartparts.Add(new OptionsForm(this));
            Host.Smartparts.Add(new OptionsForm(this));
            Host.Smartparts.Add(new OptionsForm(this));

            optionsForm.Enabled = false;
            optionsForm.Caption = "Options";
            */
            Host.Smartparts.Add(optionsForm);

            optionsForm.OnApply += new EventHandler(optionsForm_OnApply);
			optionsForm.OnCancel += new EventHandler(optionsForm_OnCancel);
			optionsForm.OnModify += new EventHandler(optionsForm_OnModify);
			Host.OnApplicationClosing += new EventHandler(Host_OnApplicationClosing);

			Host.ModuleLoader.ModuleGroupLoaded += new EventHandler(ModuleLoader_ModuleGroupLoaded);

			IsInitialized = true;
		}

        public override void Terminate()
        {
			IsInitialized = false;
            SavePersistency();
        }

		#endregion

		#region Public properties

        public IStatePersistenceService PersistenceService
        {
            get
            {
                return Services.Get<IStatePersistenceService>();
            }
        }

		public IModule Module
		{
			get
			{
				return this;
			}
		}

		#endregion

		#region Events

		public event EventHandler OnModify;
		public event EventHandler OnApply;
		public event EventHandler OnCancel;

		#endregion

		#region OptionsForm Handlers

		public void AddOptionsTab(string name, string text, Control control)
		{
			if (optionsForm == null)
			{
				throw new NullReferenceException("The options from is null.");
			}
			optionsForm.AddTabPage(name, text, control);
		}

		public void RenameOptionsTab(string name, string newText)
		{
			if (optionsForm == null)
			{
				throw new NullReferenceException("The options from is null.");
			}
			optionsForm.RenameTabPage(name, newText);
		}

		public void RemoveOptionsTab(string name)
		{
			if (optionsForm == null)
			{
				throw new NullReferenceException("The options from is null.");
			}
			optionsForm.RemoveTabPage(name);
		}

		private void optionsForm_OnModify(object sender, EventArgs e)
		{
			if (OnModify != null)
			{
				OnModify(sender, e);
			}
		}

		private void optionsForm_OnCancel(object sender, EventArgs e)
		{
			if (OnCancel != null)
			{
				OnCancel(sender, e);
			}
		}

		private void optionsForm_OnApply(object sender, EventArgs e)
		{
			if (OnApply != null)
			{
				OnApply(sender, e);
			}

			//TODO: Put this back...
			//SetCulture(mCommonTabPage.SelectedCulture);

			SavePersistency();

		}

		#endregion

		#region Event handlers

		private void ModuleLoader_ModuleGroupLoaded(object sender, EventArgs e)
		{
			if (mCommonTabPage == null)
			{
				mCommonTabPage = new CommonTabPage(this);
				mCommonTabPage.Dock = DockStyle.Fill;
				mCommonTabPage.Cultures = new List<CultureInfo>(Host.SupportedCultures);

				LoadPersistency();

				//TODO: Put this back...
				//SetCulture(mCommonTabPage.SelectedCulture);

				//optionsForm.AddTabPage("Common", LocalizationExtender.GetString("CommonTabPageHeader"), mCommonTabPage);
			}
		}

		private void LocalizationExtender_OnInvalidatingControls(object sender, EventArgs e)
		{
			RenameOptionsTab("Common", LocalizationExtender.GetString("CommonTabPageHeader"));
		}

		#endregion

		#region Persistency

		public override void SavePersistency()
		{
			if (PersistenceService != null)
			{
				PersistencyDictionary state = PersistenceService.Load(Host as IPersistable);
				mCommonTabPage.SavePersistence(state);
				optionsForm.SavePersistence(state);
				PersistenceService.Save(Host as IPersistable, state);
				Host.LogManager.WriteVerbose(this, "Persistency saved for options module.", "Options");
			}
		}

		public override void LoadPersistency()
		{
            if (PersistenceService != null)
			{
				PersistencyDictionary state = PersistenceService.Load(Host as IPersistable);
				mCommonTabPage.LoadPersistence(state);
				optionsForm.LoadPersistence(state);
				Host.LogManager.WriteVerbose(this, "Persistency loaded for options module.", "Options");
			}
		}

		#endregion

		#region Culture

		public void SetCulture(CultureInfo ci)
		{
			Host.SetCulture(ci);
		}

		#endregion

    }
}
